package main

import (
	"fmt"
)

// calculateTotal 计算订单的总价格
func calculateTotal(items map[string]float64) float64 {
	total := 0.0
	for _, price := range items {
		total += price
	}
	return total
}

// applyDiscount 创建一个偏应用函数，预设了折扣
func applyDiscount(discount float64) func(map[string]float64) float64 {
	return func(items map[string]float64) float64 {
		total := calculateTotal(items)
		return total * (1 - discount)
	}
}

// checkout 函数接受订单和支付金额，计算并返回找零
func checkout(items map[string]float64, payment float64) (float64, error) {
	discountedTotal := applyDiscount(0.10)(items) // 应用10%折扣
	if payment < discountedTotal {
		return 0, fmt.Errorf("insufficient payment: received $%.2f, needed $%.2f", payment, discountedTotal)
	}
	change := payment - discountedTotal
	return change, nil
}

func main() {
	// 假设的菜单价格
	menu := map[string]float64{
		"Burger":    9.99,
		"Fries":     2.99,
		"Soda":      1.99,
	}

	// 客户支付金额
	payment := 20.00

	// 执行结算
	change, err := checkout(menu, payment)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("Total price with 10%% discount: $%.2f\n", applyDiscount(0.10)(menu))
		fmt.Printf("Change returned: $%.2f\n", change)
	}
}